/*
 * Copyright (c) 2006 Jordan Bayliss-McCulloch
 * Email: j.baylissmcculloch@gmail.com
 */

import java.awt.*;
import java.awt.image.*;
import javax.imageio.*;
import java.io.*;

public class NewsImage {
	String template;
	BufferedImage buffer;
	
	public NewsImage(String template) {
		this.template = template;
		
		Image in = Toolkit.getDefaultToolkit().getImage( template );
		MediaTracker mt = new MediaTracker( new Container() );
		mt.addImage(in,0);
		
		try {
			mt.waitForAll();
		} catch (InterruptedException e) {
			e.printStackTrace();
		}
		
		buffer =
			new BufferedImage(in.getWidth(null), in.getHeight(null), BufferedImage.TYPE_INT_RGB);
	  
		Graphics2D graphics2d = (Graphics2D)buffer.createGraphics();
		
		graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
			      RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR);
		
		graphics2d.drawImage(in, 0, 0, in.getWidth(null), in.getHeight(null), null );
		graphics2d.dispose();
	}
	
	private Color getKeyColor( float sc) {
		float s=1.0f;
		float b=1.0f;
		sc += NewsRegion.NORMALIZE_MAX;
		
		float h = Math.abs(sc) / (NewsRegion.NORMALIZE_MAX*2.0f);
		h = Math.round(h*32.0f)/32.0f;
		
		h = (250.0f/360.0f) +  (1.0f - h) * ((360-250)/360.0f);
		
		return new Color( Color.HSBtoRGB( h,s,b) );
		/*
		float s = Math.abs(sc) / NewsRegion.NORMALIZE_MAX;
		float b = 0.93f;
		float hh = 0.0f;
		//s = 0.25f + s*0.75f;
		s = Math.round(s*20.0f)/20.0f;
		
		if (sc > 0 ) hh = (60.0f/360.0f);
		else		hh = (240.0f/360.0f);
	
		return new Color( Color.HSBtoRGB( hh,s,b) );
		*/
	
	}
	
	public void compile( NewsRegion[] regions, int width,int height,String fn) throws Exception {
		FloodFill f = new FloodFill( buffer );
		
		float min=regions[0].getScore(),max=regions[0].getScore();
		
		for (int i=0; i<regions.length; i++) {
			NewsRegion region = regions[i];
			region.update();
			float score = region.getScore();
			if (score < min) min = score;
			if (score > max) max = score;
		}
		
		//max = sign(max)*Math.max(Math.abs(max), Math.abs(min));
		//min = sign(min)*Math.min(Math.abs(max), Math.abs(min));
	
		FileOutputStream out = new FileOutputStream("data.htm");
		PrintStream p = new PrintStream( out );

		System.out.println("min\tmax\ts\tnorm");
		p.println("<script>");
		p.println("var status=[");
		for (int i=0; i<regions.length; i++) {
			NewsRegion region = regions[i];
			
			region.normalize( min, max );
			
			//p.println( region.getName() + "\t" + region.getScore() );
			p.print("\n['" + region.getName() + "'," + region.getScore() + "," + region.getStoryCount() + "]");
			 
			if (i < regions.length-1 ) p.println(", ");
			else						p.println("");
			System.out.println( min + "\t" + max + "\t" + region.getScore() + "\t" + region.getNormalizedScore());
			
			Color c = getKeyColor( region.getNormalizedScore() );

			f.replaceColor( region.getRegionColor(), c );
		}
		p.println("];");
		p.println("parent.onDataUpdate(status);");
		p.println("</script>");
		p.close();
		out.close();
		
		BufferedImage output = new BufferedImage( width, height,BufferedImage.TYPE_INT_RGB);
		Graphics2D graphics2d = (Graphics2D)output.createGraphics();
		graphics2d.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
			      RenderingHints.VALUE_INTERPOLATION_BILINEAR);
		 
		
		graphics2d.drawImage(buffer, 0, 0, width, height, null );
		
		// draw a key
		int w = 10; int h = 10;
		int divs = width/w;
		int x = width - divs*w;
		int y = height - w;
		
		for (float sc = -NewsRegion.NORMALIZE_MAX; sc < NewsRegion.NORMALIZE_MAX;sc += (NewsRegion.NORMALIZE_MAX*2)/divs) {
			
			Color c = getKeyColor( sc );

			graphics2d.setColor(c);
			graphics2d.fillRect(x,y,w,h);
			x += w;
			
		}
		
		graphics2d.dispose();
		
		ImageWriter writer = (ImageWriter) ImageIO.getImageWritersByFormatName("PNG").next();
	    ImageWriteParam param = writer.getDefaultWriteParam();

	    /*
		int quality = 100;
	    param.setCompressionMode(ImageWriteParam.MODE_EXPLICIT);
	    param.setCompressionQuality((float)quality/100);
	    */

	    writer.setOutput( ImageIO.createImageOutputStream( new File(fn)));
		
		writer.write(null, new IIOImage(output, null, null), param);
		writer.dispose();
	
		 
	}
}
